package com.wzs.util;

import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

/**
 * @author miaomiao
 * @version 1.0.0
 * @ClassName JdbcUtil.java
 * @Description 连接数据库的工具类
 * @createTime 2021-06-19- 11:27:00
 */
public class JdbcUtil {

    private static String url;
    private static String username;
    private static String password;

    static {
        InputStream is = JdbcUtil.class.getClassLoader().getResourceAsStream("jdbc.properties");//类加载器


        Properties pro = new Properties();
        try {
            pro.load(is);
        } catch (IOException e) {
            e.printStackTrace();
        }
        String driver = pro.getProperty("driver");
        url = pro.getProperty("url");
        username = pro.getProperty("user");
        password = pro.getProperty("password");


        //1.加载驱动
        try {
            Class.forName(driver);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    //2.获取连接
    public static Connection getConnection() {
        Connection conn = null;

        try {
            conn = DriverManager.getConnection(url, username, password);
            //conn = DriverManager.getConnection("com.mysql.cj.jdbc.Driver", "root", "Wzs521...");
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return conn;
    }

    public static void close(Connection conn, Statement pstm, ResultSet rs) {

        try {
            if (rs != null) {
                rs.close();
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            try {
                if (pstm != null) {
                    pstm.close();
                }
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            } finally {
                try {
                    if (conn != null) {
                        conn.close();
                    }
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
        }
    }


}












